import wizard
from osv import osv
import pooler
from tools.translate import _

_ps_form = '''<?xml version="1.0"?>
<form string="Claim and Request of payment">
    <separator string="Select Project and type of payment" colspan="4"/>
    <field name="account_id"/>
    <newline/>
    <field name="invoice_type"/>
   <!-- <separator string="Information" colspan="4"/>
    <label string="All draft account entries in this journal and period will be validated. It means you won't be able to modify their accouting fields." colspan="4"/>-->
</form>'''

_ps_fields = {
    'account_id': {'string':'Project', 'type':'many2one', 'relation':'account.analytic.account', 'required':False},
    'invoice_type':{'string':"Type of payment",'type':'selection','selection':[("'in_invoice','out_invoice'","All"),("'out_invoice'","Customer Invoice"),("'in_invoice'","Supplier Invoice")],'default': lambda *a:"'in_invoice','out_invoice'",'required':True}
}

def _action_open_window(self, cr, uid, data, context):
  #  raise wizard.except_wizard(_('UserError'), _('You must enter a period length that cannot be 0 or below !'+data['form']['invoice_type']))
    if data['form']['account_id']:
        cr.execute("Select ai.id from account_invoice ai left join account_invoice_line ail on ai.id=ail.invoice_id\
                    where account_analytic_id in((select id from account_analytic_account where parent_id="+str(data['form']['account_id'])+")\
                    union (select id from account_analytic_account where id="+str(data['form']['account_id'])+")) and partner_id in ("+','.join(map(str,data['ids']))+")))")
    else:
       cr.execute("Select ai.id from account_invoice ai where partner_id in ("+','.join(map(str,data['ids']))+")")
    invoices_id = cr.fetchall()

    return {
        'domain': "[('id', 'in', "+str(invoices_id)+"),('type','in',["+data['form']['invoice_type']+"])]",
        'name': 'Invoice List',
        'view_type': 'form',
        'view_mode': 'tree,form',
        'view_id': False,
        'res_model': 'account.invoice',
        'type': 'ir.actions.act_window'
    }

class wiz_invoice_partner_list(wizard.interface):
    states = {
        'init': {
            'actions': [],
            'result': {'type': 'form', 'arch':_ps_form, 'fields':_ps_fields, 'state':[('open','Ok'),('end','Cancel')]}
        },
        'open': {
            'actions': [],
            'result': {'type': 'action', 'action': _action_open_window, 'state':'end'}
        }
    }
wiz_invoice_partner_list('invoice.partner.list.open')

